package com.example.bt.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bt.dto.UserDto;
import com.example.bt.entity.User;
import com.example.bt.mapper.UserMapper;
import com.example.bt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: service实现层
 * @author: WangBlue
 * @create: 2024-03-06 18:11
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    /**
     * 以树形结构返回数据
     *
     * @return 用户树结构的数据
     */
    @Override
    public List<UserDto> getUserTree()
    {
        List<UserDto> allUser = userMapper.getAllUser();
        //最高级别用户集合
        List<UserDto> roots = new ArrayList<>();
        List<UserDto> res = new ArrayList<>();
        for(UserDto userDto :allUser)
        {
            //-1表示最高级别的用户
            if(userDto.getParentId() == -1)
            {
                roots.add(userDto);
            }
        }
        //从最高级别用户开始遍历，递归找到该用户的下级用户，将带有下级的最高级用户放入返回结果中
        for(UserDto userDto :roots)
        {
            userDto=buildUserTree(allUser,userDto);
            res.add(userDto);
        }
        return  res;
    }



    /**
     * 功能：根据传入的用户，获取该用户的下属集合，将集合赋值给该用户的children属性，返回该用户
     *
     * @param allUsers 所有用户
     * @param userDto dto层类
     * @return
     */
     private UserDto buildUserTree(List<UserDto> allUsers,UserDto userDto)
    {
        List<UserDto> children = new ArrayList<>();
        //遍历查到的所有用户
        for(UserDto user:allUsers)
        {
            //-1代表根节点，无需重复比较
            if(user.getParentId()== -1)
                continue;
            //当前用户的上级编号和传入的用户编号相等，表示该用户是传入用户的下级用户
            if(user.getParentId() == userDto.getId())
            {
                //递归调用，再去寻找该用户的下级用户
                user=buildUserTree(allUsers,user);
                //当前用户是该用户的一个下级用户，放入children集合内
                children.add(user);
            }
        }
        //给该用户的children属性赋值，并返回该用户
        userDto.setChildren(children);
        return userDto;
    }


}
